package com.bibrApp.difu.actvity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bibrApp.difu.R;
import com.bibrApp.difu.base.BaseActivity;
import com.bibrApp.difu.base.BasePresenter;
import com.bibrApp.difu.base.IBaseView;
import com.gyf.barlibrary.ImmersionBar;


import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.OnClick;

public class WebViewTurnTableActivity extends BaseActivity<BasePresenter> implements IBaseView {

    private ImmersionBar mImmersionBar;

    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.return_iv)
    View ivReturn;
    @BindView(R.id.tv_turntable_title)
    TextView tvTitle;
    @BindView(R.id.pb_web)
    ProgressBar progressBar;
    private Activity mContext;
    private String mTitle;

    @SuppressWarnings("unchecked")
    @Override
    protected void initPresenter() {
        presenter = new BasePresenter(this, this);
        presenter.init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_turntable_webview;
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void initView() {
        mContext = this;
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarColor(R.color.black_f0)
                .navigationBarColor(R.color.black_f0)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)
                .init();

        WebSettings settings = webView.getSettings();
        settings.setDomStorageEnabled(true);
        settings.setAppCacheMaxSize(1024 * 1024 * 8);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);

        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setBlockNetworkImage(false);

        /*设置编码方式*/
        settings.setDefaultTextEncodingName("utf-8");
        /*设置支持js*/
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        /*设置支持缩放*/
        settings.setSupportZoom(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        webView.setWebViewClient(new ReWebViewClient());
        webView.setWebChromeClient(new ReWebChromeClient());

        mTitle = getIntent().getStringExtra("title");
        if (!TextUtils.isEmpty(mTitle)) {
            tvTitle.setText(mTitle);
        } else {
            tvTitle.setText(TextUtils.isEmpty(webView.getTitle()) ? "" : webView.getTitle());
        }

        String url = getIntent().getStringExtra("url");
//        if (url.contains(BuildConfig.INVITE_API)) {
//            String newUrl = url.replace(BuildConfig.INVITE_API, "http://192.168.31.138:8080/");
//            webView.loadUrl(newUrl);
//        }
        webView.loadUrl(url);
    }


    @OnClick(R.id.return_iv)
    public void setOnClick() {
        finish();
    }


    class ReWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && webView != null) {
                webView.evaluateJavascript("javascript:$Vue.init()", value -> {
                });
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
            super.onReceivedSslError(view, handler, error);
        }
    }

    public class ReWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                }
            } else {
                if (progressBar != null) {
                    progressBar.setVisibility(View.VISIBLE);//加载完网页进度条消失
                    progressBar.setProgress(newProgress);//设置进度值
                }
            }
            super.onProgressChanged(view, newProgress);

        }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        if (webView != null) {
            webView.stopLoading();
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.removeAllViews();
            webView.destroy();
        }

    }
}